package com.lzt.flow.service;

import cn.hutool.core.util.StrUtil;
import com.lzt.flow.entity.FlowForm;
import com.lzt.flow.entity.Node;
import com.lzt.flow.slot.FlowContext;
import com.yomahub.liteflow.builder.el.LiteFlowChainELBuilder;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.FlowBus;
import com.yomahub.liteflow.flow.LiteflowResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class FlowService {

    @Resource
    private FlowExecutor flowExecutor;

    public Map<String, Object> executeFlow(FlowForm flowForm) throws Exception {
        Node node = LfParse.buildNode(flowForm.getNodeStr(), flowForm.getCurNodeId());
        String businessEl = LfParse.buildEL(node, true);
        log.info("流程执行el表达式=》{}", LfParse.buildEL(node, false));

        String chainId = "chain" + UUID.randomUUID();
        LiteFlowChainELBuilder.createChain().setChainId(chainId).setEL(businessEl).build();
        FlowContext flowContext = new FlowContext();
        flowContext.setPredictionId(flowForm.getPredictionId());
        flowContext.setFlowId(flowForm.getFlowId());
        flowContext.setRootNode(node);
        LiteflowResponse response = flowExecutor.execute2Resp(chainId, null, flowContext);
        FlowBus.removeChain(chainId);
        if (!response.isSuccess()) {
            throw response.getCause();
        }
        if (StrUtil.isEmpty(flowForm.getCurNodeId())) {
            flowForm.setCurNodeId(node.getLastNode().getId());
        }
        HashMap<String, Object> result = new HashMap<>();
        String nodeName = flowContext.getCmpNode(flowForm.getCurNodeId()).getNodeName();
        List<Map<String, String>> data = response.getContextBean(FlowContext.class).getData().get(nodeName);
        result.put("data", data);
        return result;
    }
}
